"use client";

import { useEffect, useState } from "react";
import { Modal, Form, Input, Select, Button } from "antd";
import { type Course } from "@prisma/client";
import { api } from "~/trpc/react";
import { useRouter } from "next/navigation";

interface CourseFormProps {
  mode?: 'modal' | 'page';
  open?: boolean;
  initialValues?: Course;
  onCancel?: () => void;
  onSuccess?: () => void;
}

interface CourseFormValues {
  title: string;
  description?: string;
  objectives?: string;
  prerequisites?: string;
  status: "DRAFT" | "PUBLISHED";
}

export function CourseForm({ 
  mode = 'modal',
  open, 
  initialValues, 
  onCancel, 
  onSuccess 
}: CourseFormProps) {
  const [form] = Form.useForm<CourseFormValues>();
  const [mounted, setMounted] = useState(false);
  const router = useRouter();

  const createMutation = api.courses.create.useMutation({
    onSuccess: () => {
      form.resetFields();
      onSuccess?.();
    },
  });

  const updateMutation = api.courses.update.useMutation({
    onSuccess: () => {
      form.resetFields();
      onSuccess?.();
    },
  });

  // 控制组件挂载状态
  useEffect(() => {
    if (open) {
      setMounted(true);
    }
    return () => {
      if (!open) {
        form.resetFields();
        setMounted(false);
      }
    };
  }, [open, form]);

  // 处理表单初始值
  useEffect(() => {
    if (open && initialValues && mounted) {
      form.setFieldsValue(initialValues);
    }
  }, [open, initialValues, mounted, form]);

  const handleSubmit = async (values: CourseFormValues) => {
    try {
      if (initialValues) {
        await updateMutation.mutateAsync({
          courseId: initialValues.id,
          ...values,
        });
      } else {
        await createMutation.mutateAsync(values);
      }
    } catch (error) {
      console.error("提交课程表单时出错:", error);
    }
  };

  // 处理Modal关闭后的清理
  const handleAfterClose = () => {
    form.resetFields();
    if (!open) {
      setMounted(false);
    }
  };

  const formContent = (
    <Form
      form={form}
      layout="vertical"
      onFinish={handleSubmit}
      initialValues={{
        status: "DRAFT",
        ...initialValues,
      }}
    >
      <Form.Item
        name="title"
        label="课程名称"
        rules={[{ required: true, message: "请输入课程名称" }]}
      >
        <Input />
      </Form.Item>

      <Form.Item name="description" label="课程描述">
        <Input.TextArea rows={4} />
      </Form.Item>

      <Form.Item name="objectives" label="课程目标">
        <Input.TextArea rows={4} />
      </Form.Item>

      <Form.Item name="prerequisites" label="先修要求">
        <Input.TextArea rows={4} />
      </Form.Item>

      <Form.Item name="status" label="状态">
        <Select>
          <Select.Option value="DRAFT">草稿</Select.Option>
          <Select.Option value="PUBLISHED">已发布</Select.Option>
        </Select>
      </Form.Item>

      {mode === 'page' && (
        <Form.Item>
          <Button 
            type="primary" 
            htmlType="submit"
            loading={createMutation.isLoading || updateMutation.isLoading}
            className="mr-4"
          >
            {initialValues ? '更新' : '创建'}
          </Button>
          <Button onClick={() => router.push("/courses")}>
            取消
          </Button>
        </Form.Item>
      )}
    </Form>
  );

  if (mode === 'page') {
    return formContent;
  }

  return (
    <Modal
      title={initialValues ? "编辑课程" : "新建课程"}
      open={open}
      onCancel={onCancel}
      afterClose={handleAfterClose}
      onOk={() => form.submit()}
      confirmLoading={createMutation.isLoading || updateMutation.isLoading}
      width={720}
      destroyOnClose
    >
      {mounted && formContent}
    </Modal>
  );
} 